<!-- 预约咨询 -->
<template>
  <publicPage>
    <view class="schedule">
      <view class="centerBox">
        <view class="leftBox">
          <view class="cell" style="width: 110rpx">
            <view>日期</view>
            <view>时间</view>
          </view>
          <view
            class="cell fw-7"
            style="width: 110rpx"
            v-for="(time, timeIndex) in timeList"
            :key="timeIndex"
            >{{ time.label }}</view
          >
        </view>

        <scroll-view
          scroll-x
          style="width: calc(100vw - 110rpx); border-top: solid 1px #dddddd"
        >
          <view class="rightBix">
            <view v-for="(date, dateIndex) in dataList" :key="dateIndex">
              <view class="cell tc">
                <view>{{ date.week }}</view>
                <view>{{ date.day }}</view>
              </view>
              <view
                class="cell"
                v-for="(plan, planIndex) in date.planData"
                :key="planIndex"
                @click="setDataid(plan)"
              >
                <!-- 暂无排班 -->
                <view class="box1" v-if="!plan.plantype || !plan.plannum"
                  >-</view
                >
                <!-- 预约已满 -->
                <view class="box2" v-else-if="plan.plannum === plan.surplusnum"
                  >已约满</view
                >
                <!-- 立即预约 -->
                <view :class="{ box3: postParams.dataid === plan.id }" v-else
                  >剩余{{ plan.plannum - plan.surplusnum }}</view
                >
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="linh-50 px-15 tc color9">左右滑动日历查看其他日期排班</view>

      <view class="borderTop30">
        <view class="linh-44 px-14">请你描述您要咨询的内容</view>
        <view class="borderT px-6 fz-14">
          <u--textarea
            v-model="postParams.ordtext"
            placeholder="为了更好地获得专家帮助，请尽可能详情描述想要咨询的内容"
            height="160"
            :border="false"
          ></u--textarea>
        </view>
        <view class="linh-44 px-14">上传检查报告/患处照片（选填,最多9张 ）</view>
        <view class="borderT px-14 pt-10 pb-5 fz-14">
          <Upload multiple :maxCount="9" :modelValue.sync="postParams.imgs" />
        </view>

        <view>
          <view class="borderT" style="border-color: #ddd"></view>
          <u-cell
            size="large"
            title="您要为谁咨询"
            isLink
            :border="false"
            @click="goPage('/pagesC/family/familyList?isChange=true')"
          >
            <view slot="value">
              <text>{{postParams.username || userInfo.userName}}</text>
              <text class="pl-10">{{(sex || userInfo.sex) === "0" ? "男" : "女"}}</text>
              <text class="pl-10">{{postParams.username ? calculate(birthday) : calculate(userInfo.birthday)}}</text>
            </view>
          </u-cell>
          <view class="borderT mx-15"></view>
          <u-cell
            size="large"
            title="联系方式"
            :value="postParams.userphone || userInfo.mobile"
            :border="false"
          ></u-cell>
        </view>
      </view>
      <view class="borderTop30 disFlxJS linh-50 px-15">
        <view>账户余额</view>
        <view class="color6">
          <text class="pr-5" style="color: #bb9313">{{
            userInfo.balance || 0
          }}</text>
          <text>云豆</text>
        </view>
      </view>
      <view class="borderTop30"></view>
      <view class="fexdBtn bgf">
        <view class="disFlxAC py-8 mb-5" style="background-color: #fffdf2;" @click="isRead = !isRead">
          <view class="pl-15 pr-10">
            <image v-if="isRead" src="@/static/image/image220701(14).png" style="width:36rpx;height:36rpx;" />
            <image v-else src="@/static/image/image220701(15).png" style="width:36rpx;height:36rpx;" />
          </view>
          <text>我已阅读并知晓</text>
          <text class="px-5" style="color: #bb9313" @click="goWebview">《知情同意书》</text>
        </view>
        <view class="px-15 pb-15">
          <u-button
            type="primary"
            :text="'立即预约 (' + (infoObj.makeCost || 0) + '云豆)'"
            :customStyle="{
              fontSize: '32rpx',
              borderRadius: '20rpx',
              height: '88rpx'
            }"
            :throttleTime="500"
            @click="confimCreateOrder"
          ></u-button>
        </view>
      </view>
    </view>

    <StatusPopup
      :show="czShow"
      type="error"
      btnText="去充值"
      @close="czShow = false"
      @confirm="goRecharge()"
    >
      <view class="pt-20">您的余额不足，请充值</view>
    </StatusPopup>
  </publicPage>
</template>

<script>
import orderApi from "@/api/order.js";
import StatusPopup from "../components/statusPopup.vue";
const dayjs = require("dayjs");
import Upload from '@/components/upload.vue'

export default {
  components: {
    StatusPopup,
    Upload
  },
  computed: {
    // 用户信息
    userInfo() {
      return this.$store.state.userInfo;
    },
  },
  data() {
    return {
      postParams: {
        toExps: "", // 专家ID
        callType: 2, // 预约咨询,默认不传就是即时咨询
        dataid: "", // 排班ID
        ordtext: "", // 咨询内容
        username: "",
        userphone: "", 
        imgs: [] // 患处照片
      },
      birthday: "", // 生日换算年龄
      sex: "", // 性别

      weekList: new Array("日", "一", "二", "三", "四", "五", "六"),
      timeList: [
        {
          label: "上午",
          value: 1,
        },
        {
          label: "下午",
          value: 2,
        },
      ],
      dataList: [],
      infoObj: {},
      czShow: false,

      timeText: "", // 选中日期
      isRead: false, // 是否阅读并知晓知情同意书 
    };
  },
  onLoad(options) {
    this.postParams.toExps = options.expertId;
    for (let i = 0; i < 30; i++) {
      let time = dayjs().add(i, "day");
      this.dataList.push({
        startTime: time.format("YYYY-MM-DD"),
        week: `周${this.weekList[time.day()]}`,
        day: time.format("MM/DD"),
        planData: [{ plantype: 1 }, { plantype: 2 }],
      });
    }
    this.getList();
    this.getSchedule();
  },
  // 选择家庭成员后
  onShow() {
    if (this.$store.state.sessionObj.username && this.$store.state.sessionObj.userphone) {
      this.postParams.username = this.$store.state.sessionObj.username;
      this.postParams.userphone = this.$store.state.sessionObj.userphone;
      this.birthday = this.$store.state.sessionObj.birthday
      this.sex = this.$store.state.sessionObj.sex + ''
      this.$store.commit("SET_SESSIONOBJ", {});
    } else {
      this.postParams.username = "";
      this.postParams.userphone = "";
      this.birthday = ""
      this.sex = ""
    }
  },
  methods: {
    // 获取专家详情
    async getList() {
      const { data } = await orderApi.getExpertInfo({
        expertId: this.postParams.toExps,
      });
      this.infoObj = data;
    },
    // 获取专家排班
    getSchedule() {
      orderApi
        .getPlanList({ expid: this.postParams.toExps, day: 30 })
        .then((res) => {
          res.data.forEach((v) => {
            if (v.planData.length < 2) {
              v.planData[0].plantype === 1
                ? v.planData.push({ plantype: 2 })
                : v.planData.unshift({ plantype: 1 });
            }

            v.planData.sort(function (a,b) {
              return a.plantype > b.plantype ? 1 : -1;  //升序排列
            })

            this.dataList.forEach((item, index) => {
              if (item.startTime === v.startTime) {
                item.planData = v.planData;
              }
            });
          });
        });
    },
    setDataid(plan) {
      if (plan.id) {
        this.postParams.dataid = plan.id;
        this.timeText = plan.ordStr;
      }
    },
    // 计算显示年龄
    calculate(birthday) {
      if (!birthday) return;
      const a = dayjs(birthday);
      const b = dayjs();
      return `${-a.diff(b, "year")}岁`;
    },
    // 去充值
    goRecharge() {
      this.czShow = false;
      this.goPage(
        `/pagesC/recharge/index?czPlice=${
          this.infoObj.cost - this.userInfo.balance
        }`
      );
    },
    goWebview(){
      const { miniProgram } = uni.getAccountInfoSync();
      if(process.env.NODE_ENV === 'production' && miniProgram.appId === 'wx238ad63939c8de76'){
        this.$store.commit("SET_WEBVIEWURL", 'https://user.yijianhealth.com/informedConsent');
      }else{
        this.$store.commit("SET_WEBVIEWURL", 'https://wx.yijianhealth.com/informedConsent');
      }
      this.goPage(`/pagesC/webview/index`)
		},
    // 创建预约单
    confimCreateOrder() {
      console.log(JSON.parse(JSON.stringify(this.postParams)));
      // 余额不足
      if (this.userInfo.balance < this.infoObj.makeCost) {
        this.czShow = true;
        return;
      }
      if (!this.postParams.dataid) {
        uni.showToast({
          title: "请选择预约时间",
          icon: "none",
        });
        return;
      }
      if(!this.isRead){
        uni.showToast({
          title: "请阅读《知情同意书》",
          icon: "none",
        });
        return;
      }
      
      orderApi.createOrder(this.postParams).then((res) => {
        orderApi
          .callConfirmOrder({ orderid: res.data.order })
          .then(() => {
            let name = this.postParams.username || this.userInfo.userName;
            let phone = this.postParams.userphone || this.userInfo.mobile;
            uni.redirectTo({
              url: `/pagesC/reserveExp/success?expertId=${this.postParams.toExps}&timeText=${this.timeText}&username=${name}&userphone=${phone}`,
            });
          })
          .catch((err) => {
            // 支付报错,直接跳转去订单列表,让用户自己再次支付
            uni.redirectTo({ url: "/pagesC/order/orderList" });
          });
      });
    }
  },
};
</script>
<style lang='scss' scoped>
.schedule {
  background-color: #ffffff;
  padding-bottom: 190rpx;
  .colorRED {
    color: #ff6b6b;
  }
  .centerBox {
    display: flex;
    .cell {
      width: 100rpx;
      height: 120rpx;
      font-size: 24rpx;
      border-bottom: solid 1px #dddddd;
      border-right: solid 1px #dddddd;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;
      text-align: center;
      .box1 {
        color: #808080;
      }
      .box2 {
        background-color: #ff6b6b;
        color: #ffffff;
        width: 100%;
        height: 100%;
        line-height: 120rpx;
      }
      .box3 {
        background-color: #2dbcbe;
        color: #ffffff;
        width: 100%;
        height: 100%;
        line-height: 120rpx;
      }
    }
    .leftBox {
      border-top: solid 1px #dddddd;
    }
    .rightBix {
      display: flex;
    }
  }
  .fexdBtn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
}
</style>